import { handleApi } from '@packages/lib-api';
import os from '@packages/lib-os';
import { matchByHref } from '@packages/lib-router';
// import checkEmptyAddr from './checkEmptyAddr';

const API = handleApi({
    getVersion: '/v1.0/pay/get-version-l',
});

let grayData = null;

const isGrayTest = () => {
    if (grayData && grayData.time > Date.now()) {
        return Promise.resolve(grayData.isTest)
    }
    return new Promise(resolve => {
        WPT.getData(API.getVersion, {}, res => {
            grayData = {
                isTest: res?.data?.version, // true: 新 false: 旧
                time: Date.now() + 2 * 60 * 1000
            }
            resolve(res?.data?.version);
        });
    });
}

export const residueRouter = async (uriStr, search = {}, isJump = true) => {
    search.showwxpaytitle = 1;
    let url = '';
    if (WPT.os.wjb || !await isGrayTest()) {
        const uri = decodeURIComponent(uriStr);
        if (uri?.split(',')?.length > 1) { // 老 合并付款下单页
            url = WPT.Util.urlAddQuery(`/payOrder/combineResidue${uriStr}`, search);
        } else { // 老 单个拍品下单页
            url = WPT.Util.urlAddQuery(`/payOrder/residue${uriStr}`, search);
        }
    } else {
        // 新 模块化下单页
        url = WPT.Util.urlAddQuery(`/payOrder/moduleResidue${uriStr}`, search);
    }
    if (isJump) {
        WPT.showPage(url);
    }
    return url;
}

export const payForceRedirectRouter = (flag = os.wechat && !os.xcx) => ({
    '/payOrder/residue:uri': flag,
    '/payOrder/moduleResidue:saleUris': flag,
    '/payOrder/combineResidue:saleUris': flag,
    '/payOrder/imReceipt': flag,
    '/payOrder/imTransfer:uri': flag,
    '/payment/:orderNo': flag,
    '/payOrder/liveGroup:uri': flag,
    '/payOrder/cloudWarehouseResellProduct': flag,
    '/payOrder/cloudWarehouseCreateOrder': flag,
    '/payOrder/issueSubscribe': flag,
    '/payOrder/issueBidding': flag,
    '/payOrder/cloudWarehousePay': flag,
    '/payOrder/warehouseRushSell:goodsSkuUri': flag,
    '/payOrder/cloudWarehouseOrderDetail:uri': flag,
    '/payOrder/cloudWarehousePickUp': flag,
    '/payOrder/cloudWarehouseActivityBid': flag,
    '/payOrder/warehouseConfirmOrder:skuuri': flag, //
    '/payOrder/friend:id': flag,
});

export default url => {
    const result = matchByHref(url, payForceRedirectRouter(1));

    if (!result) {
        return false;
    }
    if (os.wechat && !os.xcx) {
        return false;
    }
    WPT.showPage(url);
    return true;
};
